<?php
namespace api\modules\v1\controllers;

use yii\JPush\Client;
use yii\data\CArrayDataProvider;
use api\models\UserRelation;
use api\models\ZhiboCount;
use api\models\LikesInfor;
use api\models\ZhiboHistory;
use api\models\GiftCount;
use api\models\Gift;
use Yii;
use yii\db\Query;
use yii\base\Exception;
use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\filters\auth\QueryParamAuth;
use api\models\User;
use api\models\Realname;
use api\models\Category;
use api\models\Tag;
use api\models\Draw;
use yii\web\Session;
use ServerAPI;
use api\models\ZhiboList;
use yii\data\Pagination;


class UsersController extends ActiveController
{
    public $modelClass = 'api\models\User';
    public $verifyCode;


    //注销自有的增删改查方法
    public function actions() {
        $actions = parent::actions();
        // 禁用""index,delete" 和 "create" 操作
        unset($actions['index'],$actions['delete'], $actions['create'],$actions['update']);

        return $actions;

    }

    //临时JSON规范方法-后期需要移动
    public function var_json($code = '', $info = '', $data = array()) {
        $out['code'] = $code ?: 0;
        $out['info'] = $info ?: ($out['code'] ? 'error' : 'success');
        $out['data'] = $data ?: array();
        return $out;
    }

    //查询用户方法
    public function userInfo($phone)
    {
        $user1 = User::find()
            ->where(['phone' => $phone])
            ->one();
        return $user1;
    }

    //继承请求方法
    public function afterAction($action, $result)
    {
        $arr = parent::afterAction($action, $result); // TODO: Change the autogenerated stub

        return $arr;

    }

    //生成签名图片使用
    public function actionQianming()
    {
        $appid = "1252931330";
        $bucket = "pic";
        $secret_id = "AKID8B3kFcsszFKDvRn6HXgfT5au2ymToNab";
        $secret_key = "zmNm5D9uTq373Pkx0yqV1YOAuX3OYWL5";
        $expired = time() + 2592000;  //签名有效期
        $current = time();
        $rdm = rand();
        $srcStr = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm;
        $signStr1 = base64_encode(hash_hmac('SHA1', $srcStr, $secret_key, true).$srcStr);
        return ArrayHelper::json_var(200, '长期有效签名签名', $signStr1);
    }

    //验证码  POST   手机号（phone）   区号（quhao）
    public function actionVerification()
    {
        $quhao = $_POST['quhao'];
        $phone = $_POST['phone'];
        if (!is_null($phone)) {
            $tel = '+'.$quhao.$phone;
            $verification = rand(1000,9999);

            /*            return $count;
                        $session = Yii::$app->session;
                        $session->set('verificationCode', $verification);*/
            $data = Yii::$app->yunpian1->sendOneMessage($tel, $verification);
            return $data;
            $result = User::find()->where(['phone' => $phone])->one();
            $result->verification = $verification;
            $count = $result->save();
            if ($count) {
                return ArrayHelper::json_var(200, '发送成功');
            } else {
                return ArrayHelper::json_var(301, '内部错误');
            }
//            if($session['verification']['expire_time'] < time()) {
//                $verification = [
//                    'expire_time' => time() + 50000, //这里设置10秒过期
//                ];
//            }
        } else {
            return ArrayHelper::json_var(1, '手机号或者区号为空');
        }

    }

    //提现 验证码 POST
    public function actionTixianverify()
    {


//        return $_POST;
        $tel = $_POST['phone_all'];
        $userId = $_POST['userid'];
        $verification = rand(1000,9999);

        $tel = '+'.$tel;

        /*            return $count;
                    $session = Yii::$app->session;
                    $session->set('verificationCode', $verification);*/
        $data = Yii::$app->yunpian1->sendOneMessage($tel, $verification);
//        return $data;
        $result = User::find()->where(['user_id' => $userId])->one();
//        return $result;
        $result->verification = $verification;
        $count = $result->save();
//        return $count;
        if ($count) {
            return ArrayHelper::json_var(200, '发送成功');
        } else {
            return ArrayHelper::json_var(301, '内部错误');
        }

    }

    //停止直播 POST
    public function actionStop()
    {

    }

    //注册登录直播 POST提交  手机号（phone）   验证码verification
    public function actionLogin ()
    {
        try{
            $tel = $_POST['phone'];
            $v = intval($_POST['verification']);
            $time = date('Y-m-d H:i:s', time());
            $username = '用戶'.rand(10, 99);
            $user['info'] = $this->userInfo($tel);
            $verification = $user['info']['verification'];





//            var_dump($verification);
//            var_dump($v);


            /*        $session = Yii::$app->session;
        $user_id = $session->get('verificationCode');*/
//        var_dump($user_id);
//        return $user_id;
//        return $v;
//        判断手机号是否为空
//        return $tel;
            /*  if (!is_null($tel && $v)) {
                  //判断验证码是否正确
              if ($v == $verification){*/

//                var_dump($user_id);
//                var_dump($v);
//                return $v;
//                unset($session['verification']);



            $user['guanhzu_count'] = UserRelation::find()->andWhere(['uid' => $user['info']['id']])->count('uid');
            $user['fensi_count'] = UserRelation::find()->andWhere(['fid' => $user['info']['id']])->count('fid');
            $roomId = $user['info']['room_id'];
            $shouyi = GiftCount::find()->select('send_gift')->where(['room_id' => $roomId])->asArray()->all();

//              return shou;
            foreach ($shouyi as $value) {
                $arr[] = $value['send_gift'];
            }

            if (empty($arr)){
                $user['shouyi'] = 0;
            } else {
                $user['shouyi'] = array_sum($arr);
            }
            //判断用户是否创建
            if (empty($user['info'])){

                $id = Yii::$app->db->createCommand()->batchInsert(User::tableName(), ['phone', 'login_time', 'username'], [
                    [$tel, $time, $username],
                ])->execute(); //执行存储数据

                $result = $this->userInfo($tel);
                $userID= $result['id'] + 21000;//生成用户id
                $img = $result['icon'];
//                    $userID = $userID."A";
//                    return $userID;
//                    $yCode = array('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p');
//                    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99)); //生成accid
                $name = $result['username'];
                $p = new ServerAPI();		//php curl库
                $pwd = $p->createUserId($userID, $name, '', $img);//请求云信接口创建ID
//                    return $pwd;

//                    if ($pwd['code'] != 200){
//                        $pwd1 = $p->updateUserId($userID, $name, '', $img);//请求云信接口更新ID
//                        return $pwd1['code'];
//
//
//
//                        if ($pwd1['code'] == 200) {
//                            $pwd2 = $p->updateUserToken($userID);//请求云信接口更新ID
//
//
//
//                            return $pwd2;
//                        }
//                    }

//                    return $pwd;
                $pwd = $pwd['info']['token'];//生成的token密码
//                    return $pwd;
                $result->user_id = $userID;
                $result->pwd = $pwd;
                $count = $result->update(array('user_id','pwd'));//执行存储数据
                $user['info'] = $this->userInfo($tel);//查询更新后的数据
                $user['guanhzu_count'] = 0;
                $user['fensi_count'] = 0;
                if ($count > 0) {
                    return ArrayHelper::json_var(200, '成功', $user);
                } else {
                    return ArrayHelper::json_var(400, '数据存储失败');
                }
            } else {
                return ArrayHelper::json_var(200, '操作成功', $user);
            }

//                return $user_id;

            /* } else {

                 return ArrayHelper::json_var(2, '验证码不正确');
             }
             } else {
                 return ArrayHelper::json_var(300, '参数请求错误', $_POST);
             }*/

        } catch (\Exception $e) {
            return ArrayHelper::json_var(500, '程序错误', $e->getMessage());

        }


    }

    //退出登录
    public function actionLogout()
    {
        return ArrayHelper::json_var(200, '退出成功');
    }

    //充值接口
    public function actionPay(){

        try{

//            Yii::$app->params['bili'];
            if (!is_null($_POST)) {
                $receipt = $_POST['shouju'];
                $userId = $_POST['user_id'];
                //            $userId = $_POST[''];
                //            $time = date('Y-m-d H:i:s', time());
                //            return $time;
                $p = new ServerAPI();
                $payResult = $p->getReceiptData($receipt);
                $result = $payResult->receipt->in_app[0];
                if ($payResult->status != 0) {
                    return $payResult;
                }
                //            return $payResult;
                $money = $result->product_id;
                $transactionId = $result->transaction_id;
                $payTime = $result->purchase_date;
                $money = explode('.', $money);
                $payTime = explode(' ', $payTime);
                $money = $money['1'];
                $payTime = $payTime['1'];
                $payTime = strtotime($payTime) + 8*3600;
                $payTime = date("Y-m-d H:i:s",$payTime);
                $payList = [
                    'user_id' => $userId,
                    'pay' => $money,
                    'pay_time' => $payTime,
                    'order_id' => $transactionId,
                ];
                $count = Yii::$app->db->createCommand()->insert('pay', $payList)->execute();
                $user = User::find()->where(['user_id'=>$userId])->one(); //获取name等于test的模型
                $userMoney = $user['userMoney'] + $money;
//                return $userMoney;
                $user->userMoney = $userMoney;
                $count1 = $user->save();

                $result1 = User::find()->where(['user_id'=>$userId])->asArray()->one();
                if ($count > 0 && $count1 > 0) {
                    return ArrayHelper::json_var(200, '成功', $result1);
                } else {
                    return ArrayHelper::json_var(1, '数据库错误');
                }


            } else {
                return ArrayHelper::json_var(301, '数据为空');
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    //提现接口
    public function actionDrow()
    {

    }

    //送礼物
    public function actionSendgift()
    {
        try{
            if (!is_null($_POST)) {

                $roomId = $_POST['room_id'];
                $userId  = $_POST['user_id'];
                $giftId   = $_POST['gift_id'];

                $gifts = Gift::find()->where(['gift_id' => $giftId])->one();
                $price = $gifts['gift_money'];

                $result = User::find()->where(['user_id' => $userId])->one();
                $result->userMoney = $result['userMoney'] - $price;
                $result->send_money = $result['userMoney'] + $price;
                $count = $result->save();

//                return $count;

                $result1 = User::find()->where(['room_id' => $roomId])->one();
                $result1->userMoney = $result1['userMoney'] + $price;
                $count1 = $result1->save();
//                return $count1;

                $result4 = ZhiboList::find()->where(['room_id' => $roomId])->one();
//                return $result4['stone'];
                $result4->stone = $result4['stone'] + $price;
                $count4 = $result4->save();
//                return $count4;

                $result3 = GiftCount::find()->where(['room_id' => $roomId, 'user_id' => $userId])->one();//查询礼物流水若有则更新 没有则新增
                if ($result3) {
                    $result3->send_gift = $result3['send_gift'] + $price;
                    $count3 = $result3->save();
                } else {
                    $count3 = Yii::$app->db->createCommand()->insert('gift_count', [
                        'room_id' => $roomId,
                        'user_id' => $userId,
                        'send_gift' => $price,
                    ])->execute();
                }


                if ($count1 && $count && $count3 && $count4) {
                    $resul2 = User::find()->where(['user_id' => $userId])->one();
                    return ArrayHelper::json_var(200, '成功', $resul2['userMoney']);
                } else {
                    return ArrayHelper::json_var(1, '失败');
                }
            } else {
                return ArrayHelper::json_var(301, '无参数');
            }

        } catch (\Exception $e) {
            return ArrayHelper::json_var(500, '程序错误', $e->getMessage());
        }
    }

    //用户接口 POST
    public function actionUserinfor()
    {
        $id = $_POST['user_id'];//登录用户

            $gUserId = $_POST['g_user_id'];//查询关注用户
//            return $gUserId;

        if ($gUserId > 0) {

            $result = UserRelation::find()->select('id')->where(['AND', 'uid= '.$gUserId, 'fid = '.$id])->orwhere(['AND', 'fid= '.$gUserId, 'uid = '.$id, 'type = 2'])->all();
            if ($result) {
                $post['zhuangtai'] = 1;
            } else {
                $post['zhuangtai'] = 0;
            }
            $post['info'] = User::find()->where(['user_id' => $gUserId])->one();

            $post1['guanhzu_count1'] = UserRelation::find()->Where(['fid' => $gUserId])->count('fid');
            $post1['guanhzu_count2'] = UserRelation::find()->where(['uid' => $gUserId, 'type' => 2])->count('uid');
            $post['guanhzu_count'] = $post1['guanhzu_count1'] + $post1['guanhzu_count2'];

            $post1['fensi_count1'] = UserRelation::find()->Where(['uid' => $gUserId])->count('uid');
            $post1['fensi_count2'] = UserRelation::find()->where(['fid' => $gUserId, 'type' => 2])->count('fid');
            $post['fensi_count'] = $post1['fensi_count1'] + $post1['fensi_count2'];

            $roomId = $post['info']['room_id'];
            $shouyi = GiftCount::find()->select('send_gift')->where(['room_id' => $roomId])->asArray()->all();

//            return shou;
            foreach ($shouyi as $value) {
                $arr[] = $value['send_gift'];
            }

            if (empty($arr)){
                $post['shouyi'] = 0;
            } else {
                $post['shouyi'] = array_sum($arr);
            }

        } else {

            $post1['guanhzu_count1'] = UserRelation::find()->Where(['fid' => $id])->count('fid');
            $post1['guanhzu_count2'] = UserRelation::find()->where(['uid' => $id, 'type' => 2])->count('uid');
            $post['guanhzu_count'] = $post1['guanhzu_count1'] + $post1['guanhzu_count2'];

            $post1['fensi_count1'] = UserRelation::find()->Where(['uid' => $id])->count('uid');
            $post1['fensi_count2'] = UserRelation::find()->where(['fid' => $id, 'type' => 2])->count('fid');
            $post['fensi_count'] = $post1['fensi_count1'] + $post1['fensi_count2'];

            $post['info'] = User::find()->where(['user_id' => $id])->one();

            $roomId = $post['info']['room_id'];

            $shouyi = GiftCount::find()->select('send_gift')->where(['room_id' => $roomId])->asArray()->all();

            foreach ($shouyi as $value) {
                $arr[] = $value['send_gift'];
            }

//            $post['shouyi'] = array_sum($arr);
            if (empty($arr)){
                $post['shouyi'] = 0;
            } else {
                $post['shouyi'] = array_sum($arr);
            }


        }
        if (empty($post)){
            return ArrayHelper::json_var(2, '无数据或者数据丢失', $post);
        } else {
            return ArrayHelper::json_var(200, '查询用户信息成功', $post);
        }
        /*$id = $_POST['user_id'];//登录用户
        $gUserId = $_POST['g_user_id'];//查询关注用户
        $sql1="SELECT * FROM user WHERE user_id = ".$id;//查询用户信息
        $post['guanhzu_count'] = UserRelation::find()->andWhere(['fid' => $id])->count('fid');
        $post['fensi_count'] = UserRelation::find()->andWhere(['uid' => $id])->count('uid');
        $post['info'] = Yii::$app->db->createCommand($sql1)->queryOne();
        $str = $post['guanzhu_list'];
//        $str = explode(',', $str);
        if ($gUserId) {
            $result = User::find()->where(['guanzhu_list' => $id, 'user_id' => $gUserId])->all();
            $sql1="SELECT * FROM user WHERE user_id = ".$gUserId;//查询用户信息
            $post['guanhzu_count'] = UserRelation::find()->andWhere(['fid' => $gUserId])->count('fid');
            $post['fensi_count'] = UserRelation::find()->andWhere(['uid' => $gUserId])->count('uid');
            $post['info'] = Yii::$app->db->createCommand($sql1)->queryOne();
            if ($result) {
                $post['zhuangtai'] = 1;
            } else {
                $post['zhuangtai'] = 0;
            }
        }
        if (empty($post)){
            return ArrayHelper::json_var(2, '无数据或者数据丢失', $post);
        } else {
            return ArrayHelper::json_var(200, '查询用户信息成功', $post);
        }
        */
    }

    //历史列表
    public function actionHistoylist()
    {
        try {


            if (!is_null($_POST)) {

//                return 1111;
                $userId = $_POST['user_id'];
                $p = $_POST['page'];

//                $count = ZhiboHistory::deleteAll(['video_photo'=>null]);

                $result = ZhiboHistory::find()
                    ->select('id,video_photo,hdMp4Url,title,vid,look_nums,tag,create_time,video_name')
                    ->where(['user_id' => $userId]);
                $pages = new Pagination([
                    'totalCount' =>$result->count(),
                    'pageSize' => '50',
                    'validatePage' => false,
                    'page' => $p,
                ]);
                $model = $result->offset($pages->offset)->OrderBy(['create_time'=>SORT_DESC])->
                limit($pages->limit)->asArray()->all();

//                foreach ($model as $list) {
//                    unset($list);
//                }

                foreach($model as $key=>$value) {


                    $value['fenxiangurl'] = "http://".$_SERVER['SERVER_NAME']."/v1/defaults/mp4player?id=".$value['id'];

//
                    $model[$key]=$value;

                }
//
//
//
//
//
//
//
//
//
////                     array_push($value, '111111');
////                    print_r($model);
//
////                    return $value;
//                }
//                $model = array_values($model);

//                var_dump(array_filter($model));
//                sort($model);
//                $model = array_values($model);

//                foreach ($model as $key=>$value) {
//
//                }

//                var_dump($model);
//                return $model;



                return ArrayHelper::json_var(200, '成功', $model);


            } else {
                return ArrayHelper::json_var(301, '参数为空');
            }






        } catch (\Exception $e) {
            $e->getMessage();
        }
    }

    //删除历史
    public function actionDeletehistory()
    {
        try {
            if ($_POST) {
                $vid = $_POST['vid'];
                $count = ZhiboHistory::deleteAll(['vid' => $vid]);
                $p = new ServerAPI();
                $result = $p->deleteVideo($vid);
                if ($result['code'] != 200) {
                    return $result;
                }
                if ($count > 0) {
                    return ArrayHelper::json_var(200, '删除成功');
                }else {
                    return ArrayHelper::json_var(1, '删除失败');
                }

            } else {
                return ArrayHelper::json_var(301, '参数为空');
            }


        } catch (\Exception $e) {
            $e->getMessage();
        }
    }

    //编辑用户 POST提交  editor
    public function actionEditor()
    {

        if(!is_null($_POST)){
            $id = $_POST['user_id'];
            $username = $_POST['username'];
            $icon = $_POST['icon'];
            $info = [
                'username' => $username,
                'sex' => $_POST['sex'],
                'icon' => $icon,
//                'phone' => $_POST['phone'],
                'signature' => $_POST['signature'],
                'age' => $_POST['age'],
                'emotional' => $_POST['emotional'],
                'hometown' => $_POST['hometown'],
                'professional' => $_POST['professional'],
//                'username' => $_POST[''],
//                'username' => $_POST[''],
            ];

            $list = [
                'name' => $username,
                'cover_image' => $icon,

            ];



            $update = User::updateAll($info, 'user_id='.$id);
            $update = ZhiboList::updateAll($list, 'user_id='.$id);
            //$update_zhibolist = ZhiboList::updateAll(['cover_image => ".$_POST['icon']], 'uid='.$id);
            $user_info = User::find()
                ->where(['user_id' => $id])
                ->one();

            $p = new ServerAPI();
            $editro = $p->updateUinfo($user_info['user_id'], $user_info['username'], $user_info['icon']);

            if ($editro['code'] != 200){
                return $editro;
            }


            return ArrayHelper::json_var(200, '更新成功', $user_info);

        } else {
            return ArrayHelper::json_var(1, '提交的数据为空');
        }
    }

    //实名认证 POST提交 realname
    public function actionRealname()
    {
        if (!is_null($_POST)) {

//            $verfy = (integer)($_POST['verfication']);
//
//            $session = Yii::$app->session;
//            $re_verify = $session->get('verificationCode');

            //判断验证码是否正确
//            if ($verfy != $re_verify) {
//                return ArrayHelper::json_var(2, '验证码不正确');
//            } else {
            $user_id = $_POST['user_id'];
            $time = time();
            $realnames = [
                'phone' => $_POST['phone'],
                'userCardImg' => $_POST['userCardImg'],
                'user_id' => $user_id,
                'create_time' => $time,
            ];


            $count1 =Yii::$app->db->createCommand()->insert('realname', $realnames)->execute();
            $update_realname = User::updateAll(['is_realname' => 1, ], 'user_id=' . $user_id);
            if ($count1 > 0 && $update_realname > 0) {
                $relname_info = User::find()
                    ->where(['user_id' => $user_id])
                    ->one();
                return ArrayHelper::json_var(200, '信息已经成功提交', $relname_info);
            } else {
                return ArrayHelper::json_var(301, '数据库操作失败');
            }

        }


//        } else {
//            return ArrayHelper::json_var(1, '提交的数据为空');
//        }

    }

    //申请成为主播 name photo
    public function actionApplyanchor()
    {
        try{
            if (!is_null($_POST)) {

                $name  = $_POST['name'];
                $photo = $_POST['photo'];
                $userId = $_POST['user_id'];
                $time = time();
                $zhubo = [
                    'company_name'      => $name,
                    'certificate_photo' =>$photo,
                    'create_time' =>$time,
                    'user_id' =>$userId,
                ];
                $count = Yii::$app->db->createCommand()->insert('zhubo', $zhubo)->execute();
                $gengxin = User::updateAll(['is_anchor' => 1, ], 'user_id=' . $userId);

                if ($count > 0 && $gengxin > 0) {
                    $result = User::find()
                        ->where(['user_id' => $userId])
                        ->one();
                    return ArrayHelper::json_var(200, '成功',$result);
                } else {
                    return ArrayHelper::json_var(301, '失败');
                }

            } else {
                return ArrayHelper::json_var(301, '参数为空');
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }
    }

    //查询关注用户 attention
    public function actionAttention()
    {
        $fid = $_POST['fid'];
        $p = $_POST['page'];

        $query1 = new \yii\db\Query;
        $arr1 = $query1
            ->select([
                'user.username',
                'user.user_id',
                'user.sex',
                'user.phone',
                'user.signature',
                'user.icon',
                'user_relation.type',

            ])
            ->from('user')
            ->join('LEFT OUTER JOIN', 'user_relation',
                'user_relation.uid = user.user_id')
            ->where(['user_relation.fid' => $fid])
            ->all();
        $query2 = new \yii\db\Query;

        $arr2 = $query2
            ->select([
                'user.username',
                'user.user_id',
                'user.sex',
                'user.phone',
                'user.signature',
                'user.icon',
                'user_relation.type',

            ])
            ->from('user')
            ->join('LEFT OUTER JOIN', 'user_relation',
                'user_relation.fid = user.user_id')
            ->where(['user_relation.uid' => $fid, 'user_relation.type' => 2])
            ->all();
        $result1 = array_merge($arr1, $arr2);
        $provider = new \yii\data\ArrayDataProvider([
            'allModels' =>  $result1,

            'pagination' => [
                'pageSize' => 10,
                'page'     => $p,
            ],
        ]);

        $posts = array_values($provider->getModels());
//        return $posts;



        return ArrayHelper::json_var(200, '查询关注成功', $posts);
        /*if (!is_null($_POST)){
            $fid = $_POST['fid'];
            $p = $_POST['page'];
            $query = new Query;
            $query  ->select([
                'user.username',
                'user.user_id',
//                'user.room_id',
                'user.sex',
                'user.phone',
                'user.signature',
                'user.icon',
            ])
                ->from('user')
                ->join('LEFT OUTER JOIN', 'user_relation',
                    'user_relation.uid = user.user_id')
                ->where(['user_relation.fid' => $fid]);
            $command = $query->createCommand();
            $pages = new Pagination([
                'totalCount' =>$query->count(),
                'pageSize' => 4,
                'validatePage' => false,
                'page' => $p,
            ]);    //实例化分页类,带上参数(总条数,每页显示条数)
            $model = $query->offset($pages->offset)->limit($pages->limit)->all();
            return ArrayHelper::json_var(200, '查询关注成功', $model);
        } else {
            return ArrayHelper::json_var(1, '参数为空');
        }
        */
    }

    //用户添加关注
    public function actionAddattention()
    {
        $fid = $_POST['fid'];//粉丝fid
        $uid = $_POST['uid'];//被关注uid

        $result1 = User::find()->where(['user_id' => $uid])->one();
        $result1->guanzhu_list = $result1['guanzhu_list'].','.$fid;
        $count3 = $result1->save();//保存

        $result = UserRelation::find()->where(['fid' => $uid, 'uid' => $fid])->one();
        if($result && $count3) {
            $result->type = 2; //修改状态
            $count2 = $result->save();//保存


            //开播推送
            $tuisong = strval($uid);
            $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);
//                    $client->device()->getAliasDevices(21003);
            $response = $client->push();
            $response->setPlatform('all');
//            $response->addTag(['tag1']);
            $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
            $response->addAlias($tuisong);
            $response    ->iosNotification('增加新的粉絲啦', [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => [
//                            'type' => 0
                ]
            ]);
            $response    ->androidNotification('增加新的粉絲啦', [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => [
//                            'type' => 0
                ]
            ]);


//            return $response->send();

            try {
                $response->send();
            } catch (\JPush\Exceptions\JPushException $e) {
                // try something else here
                $e->getMessage();
            }




            return ArrayHelper::json_var(200, '添加关注成功', $count2);
        } else {
            $count = Yii::$app->db->createCommand()->insert('user_relation', [
                'fid' => $fid,
                'uid' => $uid,
                'type' => 1,
            ])->execute();
            $tuisong = strval($uid);
            $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);
//                    $client->device()->getAliasDevices(21003);
            $response = $client->push();
            $response->setPlatform('all');
//            $response->addTag(['tag1']);
            $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
            $response->addAlias($tuisong);
            $response    ->iosNotification('增加新的粉絲啦', [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => [
//                            'type' => 0
                ]
            ]);
            $response    ->androidNotification('增加新的粉絲啦', [
                'sound' => 'sound',
                'badge' => '+1',
                'extras' => [
//                            'type' => 0
                ]
            ]);
            try {
                $response->send();
            } catch (\JPush\Exceptions\JPushException $e) {
                // try something else here
                $e->getMessage();
            }




            return ArrayHelper::json_var(200, '添加关注成功', $count);
        }

        /*$fid = $_POST['fid'];//粉丝fid
        $uid = $_POST['uid'];//被关注uid

//        $result1 = UserRelation::find()->where(['name' => 'ttt'])->one();


        $id = Yii::$app->db->createCommand()->batchInsert(UserRelation::tableName(), ['uid', 'fid', 'type'], [
            [$uid, $fid, 1],
        ])->execute();
//        $result = User::find()->where(['user_id' => $uid])->one();
//        $guanzhuList = $result['guanzhu_list'].','.$fid;

        $count = User::updateAll(['guanzhu_list' => $fid], ['user_id' => $uid]);

        if ($id > 0 && $count > 0){
            return ArrayHelper::json_var(200, '添加关注成功');
        }
        return ArrayHelper::json_var(5, '程序错误');
        */
    }

    //用户取消关注 POST提交  需要用户id=》uid  取消的用户fid=》fid
    public function actionAbolishattention()
    {
        $fid = $_POST['fid'];//粉丝fid 200006
        $uid = $_POST['uid'];//被关注uid 200003

        //用户（06）只关注03
        $result = UserRelation::find()->where(['fid' => $fid, 'uid' => $uid, 'type' => 1])->one();
        $result1 = User::find()->where(['user_id' => $uid])->one();
        $result2 = explode(',', $result1['guanzhu_list']);
//        return $result2;
        foreach ($result2 as $key=>$value)
        {
            if ($value === $fid)
                unset($result2[$key]);
        }
        $guanzhulist = implode(',', $result2);
        $result1->guanzhu_list = $guanzhulist; //修改状态
        $count3 = $result1->save();//保存
        if ($result && $count3 > 0) {
            $count = $result->delete();
//            return 11111111;
//            return ArrayHelper::json_var(200, '取消关注成功', $count);
        }

        //用户（06）和03互相关注 03先关注06
        $result1 = UserRelation::find()->where(['fid' => $uid, 'uid' => $fid, 'type' => 2])->one();
        if ($result1) {
//            return 11121111;
            $result1->type = 1; //修改状态
            $count = $result1->save(); //保存
//            return ArrayHelper::json_var(200, '取消关注成功', $count1);
        }

        //用户（06）和03互相关注 06先关注03
        $result2 = UserRelation::find()->where(['fid' => $fid, 'uid' => $uid, 'type' => 2])->one();
        if ($result2) {
//            return 3;
            $result2->type = 1; //修改状态
            $result2->uid = $fid; //修改状态
            $result2->fid = $uid; //修改状态
            $count = $result2->save(); //保存
//            return ArrayHelper::json_var(200, '取消关注成功', $count2);
        }
//        return 23;
        return ArrayHelper::json_var(200, '取消关注成功', $count);


        /*$fid = $_POST['fid'];//用户fid
        $uid = $_POST['uid'];//取消关注用户uid
        $result = UserRelation::deleteAll(['uid' => $uid, 'fid' => $fid]);

        $count = User::updateAll(['guanzhu_list' => 'null'], ['user_id' => $fid]);

//        return $result;




        if ($result > 0 && $count > 0){
//            $result = $this->actionAttention($fid);
//            return $result;
            return ArrayHelper::json_var(200, '取消关注成功');
        }
        return ArrayHelper::json_var(5, '关注失败');*/
    }

    //判断是否关注 POST   被关注用户uid    需要粉丝fid
    public function actionIsattention()
    {
        if (!is_null($_POST)) {
            $uid = $_POST['uid'];
            $fid = $_POST['fid'];
            $result = UserRelation::find()->select('id')->where(['AND', 'uid= '.$uid, 'fid = '.$fid])->orwhere(['AND', 'fid= '.$uid, 'uid = '.$fid, 'type = 2'])->all();

            if ($result){
                return ArrayHelper::json_var(200, '已关注', 1);
            } else {
                return ArrayHelper::json_var(200, '未关注', 2);
            }
        }
    }

    //查询用户的粉丝POST提交 需要用户id=》uid page (fenye)
    public function actionFan()
    {
        if (!is_null($_POST)){
            $uid = $_POST['uid'];
            $p = $_POST['page'];

            $query1 = new \yii\db\Query;
            $arr1 = $query1
                ->select([
                    'user.username',
                    'user.user_id',
                    'user.sex',
                    'user.phone',
                    'user.signature',
                    'user.icon',
                    'user_relation.type',
                ])
                ->from('user')
                ->join('LEFT OUTER JOIN', 'user_relation',
                    'user_relation.fid = user.user_id')
                ->where(['user_relation.uid' => $uid])
                ->all();
            $query2 = new \yii\db\Query;

            $arr2 = $query2
                ->select([
                    'user.username',
                    'user.user_id',
                    'user.sex',
                    'user.phone',
                    'user.signature',
                    'user.icon',
                    'user_relation.type',
                ])
                ->from('user')
                ->join('LEFT OUTER JOIN', 'user_relation',
                    'user_relation.uid = user.user_id')
                ->where(['user_relation.fid' => $uid, 'user_relation.type' => 2])
                ->all();
            $result1 = array_merge($arr1, $arr2);
            $provider = new \yii\data\ArrayDataProvider([
                'allModels' => $result1,
                'sort' => [
                    'attributes' => ['user_id', 'signature', 'icon'],
                ],
                'pagination' => [
                    'pageSize' => 10,
                    'page'     => $p,
                ],
            ]);
            $posts = array_values($provider->getModels());
            return ArrayHelper::json_var(200, '查询关注成功', $posts);
        } else {
            return ArrayHelper::json_var(1, '参数为空');
        }
        /*if (!is_null($_POST)){
            $uid = $_POST['uid'];
            $p = $_POST['page'];

            $query = new Query;
            $query  ->select([
                'user.username',
                'user.user_id',
//                'user.room_id',
                'user.sex',
                'user.phone',
                'user.signature',
                'user.icon',
//                'user_follow.uid',
//                'user_follow.uid'
            ])
                ->from('user')
                ->join('LEFT OUTER JOIN', 'user_relation',
                    'user_relation.fid = user.user_id')
                ->where(['user_relation.uid' => $uid]);
            $command = $query->createCommand();
            $pages = new Pagination([
                'totalCount' =>$query->count(),
                'pageSize' => 20,
                'validatePage' => false,
                'page' => $p,
            ]);    //实例化分页类,带上参数(总条数,每页显示条数)
            $model = $query->offset($pages->offset)->limit($pages->limit)->all();
            foreach ($model as $key => $value){

//            $str = $model['guanzhu_list'];

//            $str = explode(',', $str);
                if($uid == $value['guanzhu_list']){
                    $value['zhuangtai'] = 0;
                } else {
                    $value['zhuangtai'] = 1;
                }
                $result1[] = $value;
            }

            return ArrayHelper::json_var(200, '查询关注成功', $result1);
        } else {
            return ArrayHelper::json_var(1, '参数为空');
        }*/

    }

    //创建直播间 POST 需要 title      cover_image  username(用户昵称) region（地区） user_id(用户id) tag(标签)
    public function actionCreatelive()
    {
        try{
            if (!is_null($_POST)) {
                $uuid = $_POST['user_id'];
                $zhibolist = [
                    'cover_image' => $_POST['cover_image'],
                    'name' => $_POST['username'],
                    'user_id' => $uuid,
                ];
                $chaxun = ZhiboList::find()->where(['user_id' => $uuid])->one();

                if (is_null($chaxun)) {
                    //创建频道
                    $p = new ServerAPI();
                    $list['info'] = $p->channelCreate($uuid, 0);
                    if ($list['info']['code'] != 200){
                        return $list['info'];
                    }
                    //创建聊天室
                    $createChat = $p->createChatroom($uuid);

                    $cid = $list['info']['ret']['cid'];
//                    return $createChat;
                    $zhibolist['pushUrl'] = $list['info']['ret']['pushUrl'];
                    $zhibolist['rtmpPullUrl'] = $list['info']['ret']['rtmpPullUrl'];
                    $zhibolist['hlsPullUrl'] = $list['info']['ret']['hlsPullUrl'];
                    $zhibolist['httpPullUrl'] = $list['info']['ret']['httpPullUrl'];
                    $zhibolist['room_id'] = $createChat['chatroom']['roomid'];
                    $zhibolist['cid'] = $cid;
                    $count2 =Yii::$app->db->createCommand()->insert('zhibo_list', $zhibolist)->execute();
                    $count3 = User::updateAll(['room_id' => $zhibolist['room_id'], 'cid' => $zhibolist['cid']], ['user_id' => $uuid]);
                    $chaxun1 = User::find()->where(['user_id' => $uuid])->one();
                    if ($count2 > 0 && $count3 > 0) {
                        $zhibolist['player'] = Yii::$app->params['player'];
                        $zhibolist['ban'] = $chaxun1['is_jinbo'];
                        return ArrayHelper::json_var(200, '成功', $zhibolist);
                    } else {
                        return ArrayHelper::json_var(301, '失败');
                    }

                } else {

                    $cid = $chaxun['cid'];//频道唯一cid  32位
                    $roomId = $chaxun['room_id'];//房间号
                    $p = new ServerAPI();
                    $list['info'] = $p->channelRefreshAddr($chaxun['cid']);
                    if ($list['info']['code'] != 200){
                        return $list['info'];
                    }
                    $zhibolist['pushUrl'] = $list['info']['ret']['pushUrl'];
                    $zhibolist['rtmpPullUrl'] = $list['info']['ret']['rtmpPullUrl'];
                    $zhibolist['hlsPullUrl'] = $list['info']['ret']['hlsPullUrl'];
                    $zhibolist['httpPullUrl'] = $list['info']['ret']['httpPullUrl'];
                    $zhibolist['room_id'] = $roomId;
                    $zhibolist['cid'] = $cid;
                    $zhibolist['look_nums'] = 0;
                    $zhibolist['stone'] = 0;

                    $gengxin = ZhiboList::updateAll($zhibolist, ['user_id' => $uuid]);
                    $zuixin = ZhiboList::find()->where(['user_id' => $uuid])->asArray()->one();
                    $chaxun1 = User::find()->where(['user_id' => $uuid])->one();

                    if (is_null($gengxin)) {

                        return ArrayHelper::json_var(301, '失败');

                    } else {

                        $zuixin['player'] = Yii::$app->params['player'];
                        $zuixin['ban'] = $chaxun1['is_jinbo'];
                        return ArrayHelper::json_var(200, '成功', $zuixin);

                    }
                }
            } else {
                return ArrayHelper::json_var(1, '数据为空');
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }
    }

    //测试
    public function actionCeshi()
    {
        $cIP = getenv('REMOTE_ADDR');
        $cIP1 = getenv('HTTP_X_FORWARDED_FOR');
        $cIP2 = getenv('HTTP_CLIENT_IP');
        $cIP1 ? $cIP = $cIP1 : null;
        $cIP2 ? $cIP = $cIP2 : null;
//        return gethostbyname($_SERVER["SERVER_NAME"]);
        return $cIP;




    }

    //观众退出直播间 room_id
    public function actionTuichuroom()
    {
        try{
            if (!is_null($_POST)) {

                $roomId = $_POST['room_id'];
//                $userId = $_POST['user_id'];

//                $result = ZhiboList::find()->where(['room_id' => $roomId])->one();
                $result = 111;

//                $count = ZhiboList::updateAll(['look_nums' => $result['look_nums']+1], ['room_id' => $userId]);
//                if ($count == 0) {
//                    return ArrayHelper::json_var(500, '更新失败');
//                }
//                $p = new ServerAPI();
//                $info = $p->channelRefreshAddr($result['cid']);
                if ($result == 111 ){
                    return ArrayHelper::json_var(200, '成功');
                } else {
                    return ArrayHelper::json_var(301, '失败');
                }

            } else {
                return ArrayHelper::json_var(1, '提交的数据为空');
            }

        } catch(\Exception $e) {
            $e->getMessage();
        }
    }

    //观众进入房间 room_id
    public function actionGoroom()
    {
        try{
            if (!is_null($_POST)){

                $roomId = $_POST['room_id'];

                $result = ZhiboList::find()->where(['room_id' => $roomId])->one();

                $p = new ServerAPI();
                $info = $p->getStatus($result['cid']);
                if ($info['ret']['status'] == 0) {
                    $status = 0;
                }
                if ($info['ret']['status'] == 3){
                    $status = 1;
                }

                $count = ZhiboList::updateAll(['look_nums' => $result['look_nums']+1, 'status' => $status], ['room_id' => $roomId]);
                $count1 = ZhiboHistory::updateAll(['look_nums' => $result['look_nums']+1, 'status' => $status], ['room_id' => $roomId]);

                if ($count == 0 && $count1 == 0) {
                    return ArrayHelper::json_var(500, '更新失败');
                }


//                return $info;
                if (!is_null($result)){
                    $result1 = ZhiboList::find()->where(['room_id' => $roomId])->asArray()->one();
                    $result1['player'] = Yii::$app->params['player'];
//                    return $result1;
                    return ArrayHelper::json_var(200, '成功', $result1);
                } else {
                    return ArrayHelper::json_var(301, '失败');
                }

            } else {
                return ArrayHelper::json_var(1, '参数为空');
            }

        } catch (\Exception $e) {
            $e->getMessage();
        }

    }

    //标签数据
    public function actionTaglist()
    {
        try{
            if (!is_null($_POST)) {
                $result = Tag::find()->all();
                if (!is_null($result)) {
                    return ArrayHelper::json_var(200, '成功', $result);
                } else {
                    return ArrayHelper::json_var(301, '无标签数据');
                }



            } else {
                return ArrayHelper::json_var(1, '数据为空');
            }


        } catch (\Exception $e) {
            $e->getMessage();
        }
    }

    //添加标题 标签 地区
    public function actionAddzhiboinfor()
    {
        try{
            if (!is_null($_POST)){
                $userId = $_POST['user_id'];
                $title = $_POST['title'];
                $region = $_POST['region'];
                $tag = $_POST['tag'];
                $time = time();

                $yCode = array('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p');
                $orderSn = intval(date('Y')) - 2011 . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99)); //生成accid

//                $rules = rand(100, 999) * rand(11, 999) + $time;
//                var_dump($rules);


//                return $orderSn;

                $zhibo_infor = [
                    'title' => $title,
                    'region' => $region,
                    'tag' => $tag,
                    'gift_r' => $orderSn,
                    'create_time' => $time,
                    'status' => 1,
                ];
                $count = ZhiboList::updateAll($zhibo_infor, ['user_id' => $userId]);
                $info = ZhiboList::find()->where(['user_id' => $userId])->one();
                $cid = $info['cid'];
//                $info['gift_r'] = $info['gift_rules'];
                $roomId = $info['room_id'];
                $userId = $info['user_id'];
                $coverImage = $info['cover_image'];

                //设置录制状态
                $videoName = $title.'+'.$userId.'+'.$time;
                $cid = $info['cid'];
                $needRecord = 1;
                $format = 0;
                $duration = 5;
                $p = new ServerAPI();
                $status = $p->channelRecording($cid, $needRecord, $format, $duration, $videoName);
                if ($status['code'] != 200) {
                    return $status;
                }

                //准备插入历史数据
                $zhibohistory = [
                    'create_time' => $time,
                    'video_name'  => $videoName,
                    'tag'         => $tag,
                    'title'       => $title,
                    'cid'         => $cid,
                    'room_id'     => $roomId,
                    'user_id'     => $userId,
                    'cover_image' => $coverImage,
                    'region' => $region,

                ];

                //插入直播视频文件
                $count1 =Yii::$app->db->createCommand()->insert('zhibo_history', $zhibohistory)->execute();
                if ($count1 == 0) {
                    return ArrayHelper::json_var(2, '历史记录生成失败');
                }

//                return $info;
                if ($count > 0) {
                    $gift_r = $info['gift_r'];
//                    $str=implode(array_reverse(str_split($gift_r,1))) * $info['room_id'];
//                    return $str;


                    $result = User::find()->where(['user_id' => $userId])->one();
                    $tuisong = explode(',', $result['guanzhu_list']);

                    unset($tuisong[0]);
                    if (!empty($tuisong)) {


//                    return $tuisong['username'];
                        //开播推送
                        $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);
//                    $client->device()->getAliasDevices(21003);
                        $response = $client->push();
                        $response->setPlatform('all');
//            $response->addTag(['tag1']);
                        $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
                        $response->addAlias($tuisong);
                        $response    ->iosNotification('您關註的主播開播啦'.$result['username'].'!', [
                            'sound' => 'sound',
                            'badge' => '+1',
                            'extras' => [
//                            'type' => 0
                            ]
                        ]);
                        $response    ->androidNotification('您關註的主播開播啦'.$result['username'].'!', [
                            'sound' => 'sound',
                            'badge' => '+1',
                            'extras' => [
//                            'type' => 0
                            ]
                        ]);
                        try {
                            $response->send();
                        } catch (\JPush\Exceptions\JPushException $e) {
                            // try something else here
                            $e->getMessage();
                        }

                    }
                    return ArrayHelper::json_var(200, '成功', $info);
                } else {
                    return ArrayHelper::json_var(301, '添加失败');
                }


            } else {
                return ArrayHelper::json_var(1, '提交的数据为空');
            }
        } catch (\Exception $e) {
            return ArrayHelper::json_var(500, '程序內部錯誤', $e->getMessage());
        }
    }

    //顶层导航栏
    public function actionNavbar()
    {
        try {
            if (!is_null($_POST)) {


                $result = Category::find()->all();
                if (!is_null($result)) {
                    return ArrayHelper::json_var(200, '成功', $result);
                } else {
                    return ArrayHelper::json_var(301, '失败');
                }



            } else {
                return ArrayHelper::json_var(1, '数据为空');
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }

    }

    //首页   直播 POST  需要参数顶层导航栏id page
    public function actionZhibolist()
    {
//      return $_SERVER['HTTP_CLIENT_IP'];
        try{
            if(!is_null($_POST)) {


                $delete = ZhiboList::deleteAll(['tag' => null]);




                $p = $_POST['page'];
                $id = $_POST['id'];
                $fid = $_POST['fid'];

                if ($id == 1) {
                    $sort = 'look_nums DESC';

                }
                if ($id == 2) {
                    $sort = 'status DESC';

                }
                if ($id == 3){


                    $query = new Query;
                    $query  ->select([
                        'zhibo_list.title',
                        'zhibo_list.user_id',
                        'zhibo_list.room_id',
                        'zhibo_list.cover_image',
                        'zhibo_list.name',
                        'zhibo_list.tag',
                        'zhibo_list.region',
                        'zhibo_list.look_nums',
                        'zhibo_list.status',
                        'zhibo_list.pushUrl',
                        'zhibo_list.httpPullUrl',
                        'zhibo_list.hlsPullUrl',
                        'zhibo_list.rtmpPullUrl',
                        'zhibo_list.hdMp4Url',
                        'zhibo_list.hdMp4Url',
                    ])
                        ->from('zhibo_list')
                        ->join('LEFT OUTER JOIN', 'user_relation',
                            'user_relation.uid = zhibo_list.user_id')
                        ->where(['user_relation.fid' => $fid]);
                    $command = $query->createCommand();
                    $pages = new Pagination([
                        'totalCount' =>$query->count(),
                        'pageSize' => 10,
                        'validatePage' => false,
                        'page' => $p,
                    ]);    //实例化分页类,带上参数(总条数,每页显示条数)
                    $model = $query->offset($pages->offset)->limit($pages->limit)->all();
                    return ArrayHelper::json_var(200, '查询关注成功', $model);
                }

                $data = ZhiboList::find()->andWhere([]);
                $pages = new Pagination([
                    'totalCount' =>$data->count(),
                    'pageSize' => '10',
                    'validatePage' => false,
                    'page' => $p,
                ]);
                $model = $data->offset($pages->offset)->limit($pages->limit)->orderBy($sort)->all();

                if (!is_null($model)) {
                    return ArrayHelper::json_var(200, '成功', $model);
                } else {
                    return ArrayHelper::json_var(301, '数据为空');
                }

            } else {
                return ArrayHelper::json_var(1, '提交的数据为空');
            }
        } catch (\Exception $e) {

            return ArrayHelper::json_var(500, '服务器错误', $e->getMessage());
        }
    }

    //搜索用户 按照用户名 room_id 搜索 主播
    public function actionSearch()
    {
        $db = new Query();
        $roomId = $_POST['room_id'];
        $userId = $_POST['user_id'];
        $p = $_POST['page'];
        $result=User::find()->where([
//            'is_anchor' => 1,
        ])->andwhere([
            'or',
            ['like','room_id',$roomId],
//            ['like','email',$email],
//            ['like','mobile',$mobile],
        ]);
        $pages = new Pagination([
            'totalCount' =>$result->count(),
            'pageSize' => 10,
            'validatePage' => false,
            'page' => $p,
        ]);    //实例化分页类,带上参数(总条数,每页显示条数)
        $model = $result->offset($pages->offset)->limit($pages->limit)->asArray()->all();
        foreach ($model as $key => $value){
            $str = $value['guanzhu_list'];
            $str = explode(',', $str);
            if(in_array($userId,$str)){
                $value['zhuangtai'] = 1;
//                array_push($value, $a);
            } else {
                $value['zhuangtai'] = 0;
            }
            $result1[] = $value;
        }
        return ArrayHelper::json_var(200, '查询成功', $result1);
        /*$db = new Query();
        $roomId = $_POST['room_id'];
        $userId = $_POST['user_id'];
        $p = $_POST['page'];
        $result=User::find()->where([
//            'is_anchor' => 1,
        ])->andwhere([
            'or',
            ['like','room_id',$roomId],
//            ['like','email',$email],
//            ['like','mobile',$mobile],
        ]);
        $pages = new Pagination([
            'totalCount' =>$result->count(),
            'pageSize' => 10,
            'validatePage' => false,
            'page' => $p,
        ]);    //实例化分页类,带上参数(总条数,每页显示条数)
        $result = $result->offset($pages->offset)->limit($pages->limit)->asArray()->all();
//        $guanzhu = User::find()->select('user_id')->where(['guanzhu_list' => $userId])->all();
        foreach ($result as $key => $value){

//            $str = $model['guanzhu_list'];

//            $str = explode(',', $str);
            if($userId == $value['guanzhu_list']){
                $value['zhuangtai'] = 1;
            } else {
                $value['zhuangtai'] = 0;
            }
            $result1[] = $value;
        }
//        return $result1;

        return ArrayHelper::json_var(200, '查询成功', $result1);*/
    }

    //统计观看人数 look_num   uid
    public function actionLooknums()
    {

//        return $time = date('Y-m-d H:i:s', time());
        $look_num = $_POST['look_nums'];
        $uid = $_POST['uid'];
        if ($look_num = 1) {
            $result = ZhiboCount::find()
                ->where(['uid' => $uid])
                ->one();
            return $result['id'];
        }
    }

    //点赞（取消点赞） POST  uid(用户id)  room_id(房间号)   状态为1 点赞     0  未点赞
    public function actionLikes()
    {
        if (!is_null($_POST)) {
            $uid = $_POST['uid'];
            $roomid = $_POST['room_id'];
            $islike = 1;
            $dianzan = [
                'uid' => $uid,
                'room_id' => $roomid,
                'is_like' => $islike,
            ];


            $likenums = ZhiboCount::find()
                ->where(['uid' => $uid])
                ->one();
            $likeinfo = LikesInfor::find()
                ->where(['uid' => $uid])
                ->one();
            $jian = $likenums['like_nums'] - 1;
            $zeng = $likenums['like_nums'] + 1;

            if (empty($likeinfo)) {
                $like = Yii::$app->db->createCommand()->insert('likes_infor', $dianzan)->execute();
                $zeng = [
                    'like_nums' => $zeng
                ];
                $likenums = ZhiboCount::updateAll($zeng, 'room_id='.$roomid);
                return ArrayHelper::json_var(200, '点赞成功');

            } else {

                $jian = [
                    'like_nums' => $jian,
                ];
                $likenums = ZhiboCount::updateAll($jian, 'room_id='.$roomid);

                $delete = Yii::$app->db->createCommand()->delete('likes_infor', 'uid = '.$uid)->execute();
                return ArrayHelper::json_var(200, '取消点赞成功');

            }





        } else {
            return ArrayHelper::json_var(1, '参数为空');
        }
    }

    //退出直播间   需要 room_id（房间号）
    public function actionTuichu()
    {
        try{

            if (!is_null($_POST)) {

                $roomId = $_POST['room_id'];
                $time = time();
                $result = ZhiboList::find()->where(['room_id'=>$roomId])->one();
                $longTime = $time - $result['create_time'];
                $zhibohistroy = [
                    'end_time' => $time,
                    'long_time' => $longTime,
                    'status' => 0
                ];

                $cid = $result['cid'];

                $p = new ServerAPI();
                $url = 'http://'.$_SERVER['SERVER_NAME'].'/v1/users/savevideo';

                $status = $p->changeCallback($url);

                $count1 = ZhiboHistory::updateAll($zhibohistroy, ['room_id' => $roomId, 'create_time' => $result['create_time']]);

                $count2 = ZhiboList::updateAll($zhibohistroy, ['room_id' => $roomId, ]);
//                return 11;
                if($count2 > 0 && $count1){
                    $result1 = ZhiboList::find()->where(['room_id'=>$roomId])->one();

                    return ArrayHelper::json_var(200, '退出成功', $result1);
                }else{
                    return ArrayHelper::json_var(1, '退出失败');
                }
            } else {
                return ArrayHelper::json_var(1, '参数为空');
            }

        } catch (\Exception $e) {
            $e->getMessage();
        }

    }

    //存储视频历史视频
    public function actionSavevideo()
    {

        try{
            $a = Yii::$app->request->post();
            $cid = $a['cid'];
            $vid = $a['vid'];
            $videoName = $a['video_name'];
//        $hdMp4Url = $a['hdMp4Url'];
            $videoName = strtok($videoName, '_');
            $p = new ServerAPI();
            $result = $p->getVideoPhoto($vid);
            $videoPhoto = $result['ret']['url'];//设置的视频封面
            $result1 = $p->changeVideoCover($vid, 1, $videoPhoto);
            $result2 = $p->getVidoInfor($vid);
            $videoPhoto = $result1['ret']['url'];
            $origUrl = $result2['ret']['origUrl'];

            $zhibohistory = [
                'vid' => $vid,
                'cid' => $cid,
                'video_photo' => $videoPhoto,
                'hdMp4Url' => $origUrl,
            ];


            if ($vid) {
                $count1 = ZhiboHistory::updateAll($zhibohistory, ['video_name' => $videoName]);
            } else {
                $count2 = ZhiboHistory::deleteAll(['video_name' => $videoName]);
            }







        } catch (\Exception $e) {
            $e->getMessage();
        }

    }

    //反馈帮助
    public  function actionFankui()
    {
//        var_dump($_POST);die;
        if (!is_null($_POST)) {
            $lianxi = $_POST['lianxi'];
            $name = $_POST['name'];
            $neirong = $_POST['neirong'];
            $count = Yii::$app->db->createCommand()->insert('question', [
                'contact_person' => $lianxi,
                'name' => $name,
                'problem_description' => $neirong,
            ])->execute();
//            return ($count);
            if ($count > 0) {
                return ArrayHelper::json_var(200, '成功');
            } else {
                return ArrayHelper::json_var(301, '失败');
            }

        } else {
            return ArrayHelper::json_var(1, '数据为空');
        }
    }

//    public $aa = 1;

    //提现
    public function actionTixian()
    {
//        $userId = $_POST['user_id'];
        return ArrayHelper::json_var(200, '成功', Yii::$app->params['webtixian']);
        $result = User::find()->where(['user_id' => $userId])->asArray()->one();
        $money = $result['userMoney'] / 10;
        $url = "http://123.206.64.82:7082/user/index?money=".$money;
        $this->redirect("http://www.shierdao.net/html/tixian.php?money=".$money);

//        $this->aaa;

        $data = [
//            'userMoney' => $money,
            'url' => $url,
        ];
        return ArrayHelper::json_var(200, '成功', $data);
    }

    //网页接口
    public function actionMoney()
    {
//        return $_POST;
        $userId = $_POST['userid'];
        $moeny = $_POST['money'];
        $name = $_POST['name'];
        $card = $_POST['card'];
        $bank = $_POST['bank'];
        $idCared = $_POST['Idcard'];
        $phone = $_POST['phone'];
        $verify = $_POST['verify'];
        $drawTime = date("Y-m-d h:i:s", time());

        $data = [
            'draw_money' => $moeny,
            'name' => $name,
            'card' => $card,
            'bank' => $bank,
            'Idcard' => $idCared,
            'phone' => $phone,
            'draw_time' => $drawTime,
            'user_id' => $userId,

        ];

        $count = Yii::$app->db->createCommand()->insert('draw', $data)->execute();
        if ($count > 0) {
            return ArrayHelper::json_var(200, '成功');
        } else {
            return ArrayHelper::json_var(301, '失败');
        }







    }

    //验证规则token
//    public function behaviors() {
//        return ArrayHelper::merge (parent::behaviors(), [
//            'authenticator' => [
//                'class' => QueryParamAuth::className(),
//                'optional' => [
//                    'login',
//                    'signup-test',
//
//                ],
//            ]
//        ] );
//    }

    public function actionIndex()
    {
        //$modelClass = $this->modelClass;
//        return new ActiveDataProvider([
//            'query' => $modelClass::find()->asArray(),
//
//            'pagination' => false,
//
//        ]);
    }

}